package com.exam.api.modules.order.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.exam.api.common.utils.RedisClient;
import com.exam.api.modules.goods.utils.youzan.YZOrder;
import com.exam.api.modules.goods.utils.youzan.YZRequest;
import com.exam.api.modules.order.domain.TblOrder;
import com.exam.api.modules.student.domain.TblStudent;
import com.exam.api.modules.student.service.TblStudentService;
import jakarta.annotation.Resource;
import lombok.extern.log4j.Log4j2;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.TimeUnit;


@Component
@Log4j2
public class OrderSyncDataService {

    private static final String ORDER_LOCK = "LOCK:SYNC:ORDER";
    @Resource
    private TblOrderService orderService;
    @Resource
    private YZRequest yzRequest;
    @Resource
    private TblStudentService studentService;
    @Resource
    private RedisClient redisClient;
    @Resource
    private ThreadPoolTaskExecutor appExecutor;

    @Scheduled(fixedRate = 60, timeUnit = TimeUnit.MINUTES, initialDelay = 5)
    @Transactional
    public void updateDict() {
        if (Objects.nonNull(redisClient.get(ORDER_LOCK))) {
            log.info("同步订单获取到锁，不执行本次逻辑");
            return;
        }
        redisClient.set(ORDER_LOCK,1);
        redisClient.expire(ORDER_LOCK, 600);
        try{
            refreshYzOrderList();
        }finally {
            redisClient.del(ORDER_LOCK);
            log.info("选座布局刷新完成");
        }
    }

    /**
     * 同步状态，返回true为正在执行中，false为未执行
     * @return
     */
    public Boolean syncStatus(){
        return Objects.nonNull(redisClient.get(ORDER_LOCK));
    }

    public void syncRefreshYzOrderList() {
        appExecutor.execute(this::updateDict);
    }


    @Transactional
    public void refreshYzOrderList() {

        try {
            LocalDateTime endTime = LocalDateTime.now();
            LocalDateTime startTime = endTime.minusHours(2);
            List<YZOrder> orders = yzRequest.getOrderList(startTime, endTime);
            List<TblOrder> insertOrderList = new ArrayList<>();
            List<TblOrder> updateOrderList = new ArrayList<>();
            orders.forEach(order -> {
                //先查询数据库是否存在此订单
                Optional<TblOrder> oldOrderOpt = orderService.lambdaQuery().eq(TblOrder::getOrderId, order.getOrderId()).oneOpt();
                if(oldOrderOpt.isEmpty()){
                    if (StrUtil.isNotEmpty(order.getBuyerPhone())){
                        TblStudent student = studentService.getStudentByTel(order.getBuyerPhone());
                        TblOrder tblOrder = BeanUtil.copyProperties(order, TblOrder.class);
                        tblOrder.setUserId(student.getId());
                        insertOrderList.add(tblOrder);
                    }
                }else {
                    // 更新
                }
            });

            if(CollUtil.isNotEmpty(insertOrderList)){
                orderService.saveBatch(insertOrderList);
            }
            if(CollUtil.isNotEmpty(updateOrderList)){
                orderService.updateBatchById(updateOrderList);
            }

        }catch (Exception e){
            log.error(e.getLocalizedMessage());
        }
    }
}
